package com.henry.base.concurrency.aio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;

public class AioReadHandler implements CompletionHandler<Integer,ByteBuffer> {
    private AsynchronousSocketChannel socketChannel;

    public AioReadHandler(AsynchronousSocketChannel socketChannel) {
        this.socketChannel = socketChannel;
    }

    public void cancelled(ByteBuffer buffer) {
        System.out.println("cancelled");
    }

    private static CharsetDecoder decoder = Charset.forName("UTF-8").newDecoder();

    @Override
    public void completed(Integer result, ByteBuffer buffer) {
        if (result > 0) {
            buffer.flip();
            try {
                System.out.println("收到"+socketChannel.getRemoteAddress().toString()+"的消息:"+decoder.decode(buffer));
            } catch (CharacterCodingException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            socketChannel.read(buffer, buffer, this);
        }
    }

    @Override
    public void failed(Throwable exc, ByteBuffer attachment) {

    }
}
